#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>

#include "share_mem.h"
#include "ring_buf.h"
#include "clog_lib.h"
#include "clog_common.h"

void sigterm_handler(int signum) {
    clog_system_deinit_interface();
    exit(0);
}

int main(int argc, char* argv[])
{
    int32_t ret;
    int32_t data_len = 0;
    uint8_t* data = NULL;
    clog_entry_t *entry = NULL;
    size_t out_len = 0;
    signal(SIGINT, sigterm_handler);
    signal(SIGTERM, sigterm_handler);

    const char *cfg_file = argv[1];
    if (access(cfg_file, F_OK) == -1) {
        fprintf(stderr, "Config file %s does not exist\n", cfg_file);
        return -1;
    }

    entry = malloc(sizeof(clog_entry_t));

    ret = clog_system_init_interface(cfg_file);
    if (ret != 0) {
        fprintf(stderr, "clog_system_init_interface failed, ret=%d\n", ret);
        return -1;
    }


    while (1)
    {
        ret = shmem_ring_dequeue(entry, &data_len);
        if (ret == 0 && data_len > 0) {
            if (data_len < 40960) {
                entry->message[data_len] = '\0';
            } else {
                entry->message[40959] = '\0';
            }
            
            clog_log_error("read shared mem data: %s", entry->message);
            ret = write_one_log_message_to_ring_buf_interface(entry->message, entry->message_len);
            if (ret != 0) {
                printf("write_one_log_message_to_ring_buf_interface failed, ret=%d\n", ret);
                continue;
            }
        } else {
            printf("failed to read shared mem or no data available, ret: %d, data_len: %d\n", ret, data_len);
            usleep(100000);
        }
    }
    return 0;
}
